﻿using System.Data.Entity;
using CarShop.Data.EntityFramework.Interfaces;
using CarShop.Data.EntityFramework.Mappings;
using CarShop.Domain.Entities;

namespace CarShop.Data.EntityFramework
{
    public class CarShopContext : DbContext, IQueryableUnitOfWork
    {
        public DbSet<Car> Cars { get; set; }
        public DbSet<CarBrand> CarBrands { get; set; }
        public DbSet<CarType> CarTypes { get; set; }
        public DbSet<CarStatus> CarStatuses { get; set; }
        public DbSet<Order> Order { get; set; }
        public DbSet<OrderStatus> OrderStatuses { get; set; }
        public DbSet<Picture> Pictures { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<UserInfo> UserInfos { get; set; }


        public CarShopContext() : base("CarShopDb")
        {
        }

        public CarShopContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        public void Commit()
        {
            this.SaveChanges();

            //try
            //{
            //    this.SaveChanges();
            //}
            //catch (Exception ex)
            //{
            //    Exception exceptionToThrow;
            //    var rethrow = ExceptionManagerFactory.CreateExceptionManager().HandleException(ex, ExceptionPolicy.DataAccess, out exceptionToThrow);
            //    if (rethrow)
            //    {
            //        throw exceptionToThrow;
            //    }
            //}
        }

        public IDbSet<TEntity> CreateSet<TEntity>() where TEntity : class
        {
            return base.Set<TEntity>();
        }

        public void Attach<TEntity>(TEntity entity) where TEntity : class
        {
            base.Entry(entity).State = EntityState.Unchanged;
        }

        public void SetModified<TEntity>(TEntity entity) where TEntity : class
        {
            base.Entry(entity).State = EntityState.Modified;
        }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new RoleConfiguration());
            modelBuilder.Configurations.Add(new UserConfiguration());
            modelBuilder.Configurations.Add(new CarBrandConfiguration());
            modelBuilder.Configurations.Add(new CarTypeConfiguration());
            modelBuilder.Configurations.Add(new CarConfiguration());
            modelBuilder.Configurations.Add(new OrderConfiguration());
            modelBuilder.Configurations.Add(new OrderStatusConfiguration());
            modelBuilder.Configurations.Add(new PictureConfiguration());
            modelBuilder.Configurations.Add(new UserInfoConfiguration());
        }

    }
}
